package org.example.springboot3.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import jakarta.annotation.Resource;
import org.example.springboot3.common.Result;
import org.example.springboot3.entity.Employee;
import org.example.springboot3.service.BlogService;
import org.example.springboot3.service.EmployeeService;

import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
public class WebController {

    @Resource
    private EmployeeService employeeService;
    private BlogService blogService;

    // 构造函数，用于注入员工服务接口的实例
    public WebController(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    @PostMapping("/login")
    public Result login(@RequestBody Employee employee) {
        Employee data = employeeService.login(employee);// 调用员工服务接口的 login 方法进行登录验证，返回员工信息
        return Result.success(data); // 返回包含员工信息的成功响应结果
    }

    @PostMapping("/signin")
    public Result register(@RequestBody Employee employee) {
        employeeService.register(employee);
        return Result.success();
    }
    @PutMapping("/updatePassword")
    public Result updatePassword(@RequestBody Employee employee) {
        employeeService.updatePassword(employee);
        return Result.success();
    }

    @GetMapping("/lineData")
    public Result getLineData() {
        Map<String, Object> map = new HashMap<>();
        Date date = new Date();  // 今天当前的时间
        DateTime start = DateUtil.offsetDay(date, -7); // 起始日期
        List<DateTime> dateTimeList = DateUtil.rangeToList(start, date, DateField.DAY_OF_YEAR);
        // 把 DateTime 类型的日期转换成  字符串类型的日期  ["10月22日", "10月23日"...]
        List<String> dateStrList = dateTimeList.stream().map(dateTime -> DateUtil.format(dateTime, "MM月dd日"))
                .sorted(Comparator.naturalOrder()).collect(Collectors.toList());
        map.put("date", dateStrList);  // x轴数据

        List<Integer> countList = new ArrayList<>();
        for (DateTime day : dateTimeList) {
            // 10月22日
            String dayFormat = DateUtil.formatDate(day);  // 2023-10-22
            // 获取当天所有的发布的文章的数量
            Integer count = blogService.selectCountByDate(dayFormat);
            countList.add(count);
        }
        map.put("count", countList);  // y轴发布文章的数量数据
        return Result.success(map);
    }
}//




// http://localhost:9090/
